package com.example.photograph.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.photograph.domain.Md5Util;
import com.example.photograph.domain.ResutltAndCookie;
import org.apache.commons.lang3.StringUtils;

import java.net.HttpCookie;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author panhm
 * @date 2022-06-15
 * @Description:
 */
public class HutoolUtil {
   static Pattern pattern= Pattern.compile("\'((?!\').)+\'");
    public  static ResutltAndCookie getTokenAndCookie(){
        HttpResponse execute = HttpRequest.get("https://wap.fj.10086.cn/store/login").execute();

        String body = execute.body();
        String token ="";
        for (String s : body.split("\\n")) {
            if (s.contains("_token")){
                token =s.trim().replace("_token:","").replace(",","").replace("'","").trim();
                break;
            }
        }
        return new ResutltAndCookie(token,execute.getCookieStr());
    }
    public  static ResutltAndCookie login(String phone,String code){
        ResutltAndCookie resutltAndCookie = getTokenAndCookie();
        JSONObject json = new JSONObject();
        json.put("code",  Md5Util.toMD5(code));
        json.put("mobile",phone);
        json.put("_token", resutltAndCookie.getResult());
        HttpResponse execute = HttpRequest.post("https://wap.fj.10086.cn/store/login_sms")
                .header("Accept", "application/json, text/plain, */*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json; charset=UTF-8")
                .header("Cookie", resutltAndCookie.getCookie())
                .body(JSON.toJSONString(json))
                .execute();
        String result =unicode2String (execute.body());
        if (result.equals("{\"message\":\"验证码不正确\"}")){
            throw new RuntimeException("验证码不正确");
        }
        String cookie = execute.getCookieStr();
        return new ResutltAndCookie(result,cookie);
    }



    private static   String unicode2String(String unicode) {
        if (StringUtils.isBlank(unicode)) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        int i = -1;
        int pos = 0;

        while ((i = unicode.indexOf("\\u", pos)) != -1) {
            sb.append(unicode.substring(pos, i));
            if (i + 5 < unicode.length()) {
                pos = i + 6;
                sb.append((char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16));
            }
        }
        //如果pos位置后，有非中文字符，直接添加
        sb.append(unicode.substring(pos));

        return sb.toString();
    }

}